package com.example.studyPlatform.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.example.studyPlatform.controller.api.kit.UrlUtils.isResources;
import static com.example.studyPlatform.controller.api.kit.UrlUtils.normUrl;

@Component
public class ThemeConfig implements Filter {
    // 设置主题
    public String theme;

    public ThemeConfig(@Value("${custom.theme}") String theme) {
        this.theme = normUrl(theme);
    }

    // 请求api不需要用render路由
    public String render(String path) {
        if (StringUtils.isBlank(theme))
            return normUrl(path);
        else
            return "theme/" + theme + "/" + normUrl(path);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String url = request.getRequestURI();
            if (isResources(url)) {
                ((HttpServletResponse) servletResponse).sendRedirect(request.getRequestURI().replaceFirst("/theme/", "/"+theme+"/"));
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }
}
